#!/use/bin/python
# coding=utf-8
# 核心指标-经验值算法-作息时间准确率
import datetime
import pymysql
import json

import requests
from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.150.109', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql,conf=2):
    if conf == 1:
        conn, cur = getConfConnection()
    else:
        conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        num = numResult[0]
    return num

#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            rate = round(X *100 / Y, 2)
    return rate

# 计算总体服务开启率
def insertOpenRate(date,serId):
    try:
        conn, cur = getDataConnection()
        # 覆盖用户数
        feedNumber = selectNumBySql(f"select t.cumulate_num from analysis_feed_number t where t.service_key ='{serId}' and t.ref_date = '{date}'")
        # 订阅用户数
        subscribeNumber = selectNumBySql(
            f"select t.cumulate_num from analysis_subscribe_number t where t.service_key ='{serId}' and t.execute_flag = 1 and t.ref_date = '{date}'", )
        # 计算 服务开启率
        openRate = getRateByXY(subscribeNumber,feedNumber)
        logDetail = f"{date}日{serId} -覆盖用户数:{feedNumber},订阅用户数:{subscribeNumber},开启率:{openRate}"
        print(logDetail)
        url = "http://192.168.2.176:8080/star-rocks/common/data/access/result"
        #url = "https://api-bdata.skysrt.com/star-rocks/common/data/access/result" #正式

        payload = json.dumps({
            "indexId": "T00015",
            "indexValue": f"{openRate}",
            "dt": f"{date}",
            "indexType": "1",
            "dataReportingTeam": "主动交互"
        })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload)

        print(response.text)

    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date


if __name__ == '__main__':
    d = 1
    date = getdate(d)
    insertOpenRate(date,'all')
    print (f"{date} 日期,上传到大数据指标<服务总开启率>" )


